<template>
  <view class="container">
    <my-navbar-top></my-navbar-top>

    <view class="order-page">
      <view class="order-header"> 我的订单 </view>
      <view class="order-tab">
        <view
          class="order-tab-item"
          v-for="(item, index) in tabList"
          :key="index"
          :class="{ active: tabIndex == item.value }"
          @click="handleTabClick(item.value)"
        >
          <view class="order-tab-item-title">{{ item.name }}</view>
        </view>
      </view>
      <view class="order-list">
        <scroll-view
          scroll-y
          bindscrolltolower="handleScrollToLower"
          style="height: 100%"
        >
          <view v-if="orderList.length !== 0 && !isLoad">
            <view
              class="order-item"
              v-for="(item, index) in orderList"
              :key="index"
              @click="handleOrderDetail(item)"
            >
              <view class="order-header">
                <view class="order-no">订单编号：{{ item.erp_order_no }}</view>
                <view class="order-status">{{ item.status_name }}</view>
              </view>
              <view class="order-goods">
                <!-- 物流相关信息 -->
                <view
                  class="logistics"
                  v-if="item.logistics"
                  @click.stop="handleLogistics(item)"
                >
                  <view class="logistics-title">包裹</view>
                  <view class="logistics-status">{{
                    item.logistics.data.logisticsStatusDesc
                  }}</view>
                  <view class="logistics-desc"
                    >{{ item.logistics.data.theLastMessage }}
                  </view>
                  <image
                    src="/static/images/gray-right.png"
                    mode="scaleToFill"
                  />
                </view>

                <order-item
                  v-for="(goods, gIx) in JSON.parse(item.pay_info)"
                  :key="gIx"
                  :item="goods"
                ></order-item>
              </view>
              <view class="order-footer">
                <view class="money">
                  <view class="money-title">实付</view>
                  <view class="money-value">￥{{ item.price }}</view>
                </view>
                <view class="buttons">
                  <view
                    class="button plain"
                    v-if="[2].includes(item.status)"
                    @click.stop="handleCancelOrder(item)"
                    >取消订单</view
                  >
                  <view
                    class="button"
                    v-if="item.status == 2"
                    @click.stop="handlePay(item)"
                    >立即支付</view
                  >
                  <view
                    class="button plain"
                    v-if="
                      [3, 4, 5].includes(item.status) && item.is_invoice != 1
                    "
                    @click.stop="handleApplyInvoice(item)"
                    >申请开票
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="order-box" v-if="orderList.length === 0 && !isLoad">
            <view>暂无订单，快去逛逛吧</view>
            <view class="go-shop" @click="handleGoShop">去逛逛</view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 库存不足 -->
    <stock-popup ref="stockPopup"></stock-popup>
	<!-- 限购弹框 需要传入文案 -->
	<stock-popup ref="limitPopup" text1="您已超过今日最大购买限额" text2="请理性消费" @close="limitClose"></stock-popup>
  </view>
</template>

<script>
import orderItem from '@/components/goods/orderItem.vue'
import stockPopup from '@/components/stockPopup.vue'
export default {
  name: 'order',
  components: {
    orderItem,
    stockPopup,
  },
  data() {
    return {
      isLoad: true,
      orderList: [],
      tabList: [
        {
          name: '全部',
          value: 1,
        },
        {
          name: '待支付',
          value: 2,
        },
        {
          name: '待发货',
          value: 3,
        },
        {
          name: '待收货',
          value: 4,
        },
        {
          name: '已完成',
          value: 5,
        },
        // {
        //   name: '已取消',
        //   value: 6,
        // },
      ],
      tabIndex: 1, // 1 全部  2 待支付   3待发货   4 待收货  5 已完成   6 已取消
      page: 1,
      isEnd: false,
    }
  },
  onShow() {
    this.getOrderList(true)

    // this.$api
    //   .logisticsInfo({
    //     order_id: 108,
    //   })
    //   .then((res) => {
    //     console.log(res)
    //   })
  },
  onLoad(options) {
    this.tabIndex = options.type || 1
    console.log(this.tabIndex, '--')
  },
  methods: {
    handleTabClick(value) {
      this.tabIndex = value
      this.getOrderList(true)
    },
    getOrderList(init) {
      this.isLoad = true
      this.$util.showLoading()
      if (init) {
        this.page = 1
        this.orderList = []
        this.isEnd = false
      }
      this.$api
        .orderList({
          page: this.page,
          type: this.tabIndex,
        })
        .then((res) => {
          console.log(res)
          if (res.code == 0) {
            let list = res.data || []
            this.orderList = this.orderList.concat(list)
            if (list.length == 0) {
              this.isEnd = true
            }
          }
        })
        .finally(() => {
          this.isLoad = false
        })
    },
    handleScrollToLower() {
      if (this.isEnd) {
        return
      }
      this.page = this.page + 1
      this.getOrderList(false)
    },
    handleCancelOrder(item) {
      uni.showModal({
        title: '提示',
        content: '确定取消订单吗？',
        success: (res) => {
          if (res.confirm) {
            this.cancelOrder(item)
          }
        },
      })
    },
	limitClose() {
	  // 可以干一些事情
	},
    cancelOrder(item) {
      this.$api
        .orderCancel({
          order_id: item.id,
        })
        .then((res) => {
          console.log(res)
          if (res.code == 0) {
            uni.showToast({
              title: '取消成功',
              icon: 'success',
            })
            this.getOrderList(true)
          }
        })
    },
    handlePay(item) {
      console.log(item)
      this.$api
        .orderPay({
          order_id: item.id || '',
        })
        .then((res) => {
          if (res.code == 0) {
            // 发起支付
            this.pay(res.data)
            return
          } else if (res.code == -1) {
            this.$refs.stockPopup.openPopup()
		  } else if (res.code == -2) {
			  this.$refs.limitPopup.openPopup()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })
    },
    // 执行支付
    pay(data) {
      console.log(data)
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success: (res) => {
          console.log(res)
          if (res.errMsg == 'requestPayment:ok') {
            uni.showToast({
              title: '支付成功',
              icon: 'success',
            })
            uni.navigateTo({
              url:
                '/pages/settlement/status/index?status=success&order_id=' +
                data.order_id +
                '&order_no=' +
                data.order_no,
            })
          }
        },
        fail: (res) => {
          console.log(res, 'fail')
          if (res.errMsg == 'requestPayment:fail cancel') {
            uni.showToast({
              title: '支付取消',
              icon: 'none',
            })
            setTimeout(() => {
              uni.navigateTo({
                url:
                  '/pages/settlement/status/index?status=fail&order_id=' +
                  data.order_id +
                  '&order_no=' +
                  data.order_no,
              })
            }, 500)
          }
        },
      })
    },
    handleApplyInvoice(item) {
      uni.navigateTo({
        url: `/pages/order/invoice/index?order_id=${item.id}`,
      })
    },
    handleOrderDetail(item) {
      uni.navigateTo({
        url: `/pages/order/detail/index?out_trade_no=${item.order_no}`,
      })
    },
    handleGoShop() {
      uni.switchTab({
        url: '/pages/home/index',
      })
    },
    handleLogistics(item) {
      uni.navigateTo({
        url: `/pages/order/logistics/index?order_id=${item.id}`,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
